package com.huang;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class CompleteFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        extracted();


    }

    private static void extracted() throws InterruptedException, ExecutionException {
        //可顺序执行  也可以全异步
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(1111);
            return 1;
        }).thenApply((f) -> {
            System.out.println(f+2);
            return f + 2;
        }).whenComplete((r, e) -> {
            if (e == null) {
                System.out.println(r);
            }
        });


        System.out.println("继续上课");
//        System.out.println(future.join());
//        System.out.println(future.get()+"sssss");
       TimeUnit.SECONDS.sleep(5);    //需要等待一下CompletableFuture 任务执行完   主线程结束 直接退出  不会等待其他完成所以需要等
    }

    static void test2() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {
            System.out.println("买水");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{
            System.out.println("买饭");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        });
        System.out.println(f2.get());
        CompletableFuture<Void> f3 =  CompletableFuture.runAsync(()->{
            System.out.println("买药");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("继续上课。。。。");
    }
   static   void    test1() throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask<Integer>(()->{
            System.out.println("班长去买水");
            TimeUnit.SECONDS.sleep(2);
            return 1;
        });
        new Thread(futureTask).start();
        System.out.println("继续讲课。。。");
        // get() 会阻塞   一般放在最后面  但是还是解决不了本质

        while (true){
            if(futureTask.isDone()){
                System.out.println(futureTask.get());
                break;
            }else {
                System.out.println("还在等待中。。。。。");
            }
        }

    }
}

